# -*- coding: utf-8 -*-

import json
import socket

try:
    # Pytnon 3
    bytes
except:
    # Pytnon 2
    bytes = str

try:
    str = unicode
except:
    pass


max_packet_size = 32*1024

def sendjmsg_tcp(address, data, timeout=5):
    # Create a socket (SOCK_STREAM means a TCP socket)
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    sock.settimeout(timeout)
    # Connect to server and send data
    sock.connect(address)
    sock.send( json.dumps(data).encode("utf-8") )

    # Receive data from the server and shut down
    received = []
    done = False
    while not done:
        try:
            chunk = sock.recv(max_packet_size).decode("utf-8")
        except:
            chunk = ""
        
        chunk_length = len(chunk)
        if not chunk_length or chunk_length < max_packet_size:
            done = True
        received.append( chunk )
    
    received = "".join(received)
    
    sock.close()
    
    return json.loads(received.strip())

def sendjmsg_udp(address, data, timeout=5):
    # Create a socket (SOCK_STREAM means a TCP socket)
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

    sock.settimeout(timeout)
    # Connect to server and send data
    sock.sendto( json.dumps(data).encode("utf-8"), address)

    received, address = sock.recvfrom(max_packet_size)

    sock.close()

    return json.loads( received.decode("utf-8") )


sendjmsg = sendjmsg_udp